#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "Fifo.hpp"
#include "time.hpp"
using namespace std;

const string gpath = "/home/yjz/linux/sharemem";
// 操作系统申请空间，是按块为单位的，4KB、2KB...
const int gprojId = 0x666;
const int gshmsize = 4096;
const mode_t gmode = 0666;

class ShareMemory
{
private:
    void CreatShmHelp(int flag)
    {
        _key = ftok(gpath.c_str(), gprojId);
        if (_key < 0)
        {
            cerr << "ftok error" << endl;
            return;
        }

        _shmid = shmget(_key, gshmsize, flag);
        if (_shmid < 0)
        {
            cerr << "shmget error" << endl;
            return;
        }
    }

public:
    ShareMemory()
        : _key(-1), _shmid(-1), _addr(nullptr)
    {
    }

    ~ShareMemory()
    {
    }

    void CreatShm()
    {
        if (_shmid == -1)
        {
            CreatShmHelp(IPC_CREAT | IPC_EXCL | gmode);
        }
    }

    void GetShm()
    {
        CreatShmHelp(IPC_CREAT);
    }

    void AttachShm()
    {
        _addr = shmat(_shmid, nullptr, 0);
        if ((long long)_addr == -1)
        {
            cout << "attach error" << endl;
        }
    }

    void DetachShm()
    {
        if (_addr != nullptr)
        {
            shmdt(_addr);
            cout << "shmdt done" << endl;
        }
    }

    void DeleteShm()
    {
        shmctl(_shmid, IPC_RMID, nullptr);
    }

    void *GetAddr()
    {
        return _addr;
    }

    void ShmMeta()
    {
    }

private:
    key_t _key;
    int _shmid;
    void *_addr;
};

ShareMemory shm;

struct data
{
    char status[32];
    char lasttime[128];
    char image[128];
};